const { ipcRenderer } = require('electron');

// 使用原生fetch或者创建一个兼容的fetch函数
let fetch;
try {
    fetch = require('node-fetch');
} catch (e) {
    // 如果node-fetch不可用，使用原生fetch或XMLHttpRequest
    if (typeof globalThis.fetch !== 'undefined') {
        fetch = globalThis.fetch.bind(globalThis);
    } else {
        // 创建一个简单的fetch替代
        fetch = async function(url, options = {}) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open(options.method || 'GET', url);
                xhr.onload = () => {
                    resolve({
                        ok: xhr.status >= 200 && xhr.status < 300,
                        status: xhr.status,
                        statusText: xhr.statusText,
                        json: async () => JSON.parse(xhr.responseText)
                    });
                };
                xhr.onerror = () => reject(new Error('Network error'));
                xhr.send(options.body);
            });
        };
    }
}

// 配置
let settings = {
    opacity: 0.9,
    width: 400,
    height: 600,
    alwaysOnTop: true,
    refreshInterval: 2000
};

let refreshTimer = null;

// 初始化应用
async function init() {
    try {
        // 获取当前设置
        settings = await ipcRenderer.invoke('get-settings');
        updateSettingsUI();
        
        // 绑定事件
        bindEvents();
        
        // 开始数据更新
        startDataRefresh();
        
        console.log('悬浮窗初始化完成');
    } catch (error) {
        console.error('初始化失败:', error);
        showError('初始化失败: ' + error.message);
    }
}

// 绑定事件
function bindEvents() {
    // 标题栏按钮
    document.getElementById('settingsBtn').addEventListener('click', toggleSettings);
    document.getElementById('minimizeBtn').addEventListener('click', minimizeWindow);
    document.getElementById('closeBtn').addEventListener('click', closeWindow);
    
    // 设置面板
    document.getElementById('closeSettings').addEventListener('click', hideSettings);
    
    // 设置控件
    document.getElementById('opacitySlider').addEventListener('input', updateOpacity);
    document.getElementById('widthInput').addEventListener('change', updateSize);
    document.getElementById('heightInput').addEventListener('change', updateSize);
    document.getElementById('alwaysOnTopCheck').addEventListener('change', updateAlwaysOnTop);
    document.getElementById('refreshInterval').addEventListener('change', updateRefreshInterval);
    document.getElementById('resetPosition').addEventListener('click', resetPosition);
}

// 获取伤害数据
async function fetchDamageData() {
    try {
        const response = await fetch('http://localhost:8989/api/data');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        if (data.code !== 0) {
            throw new Error(data.msg || '服务器返回错误');
        }
        
        return data.user || {};
    } catch (error) {
        console.error('获取数据失败:', error);
        throw error;
    }
}

// 更新显示数据
async function updateDisplay() {
    const damageList = document.getElementById('damageList');
    
    try {
        const userData = await fetchDamageData();
        
        if (Object.keys(userData).length === 0) {
            damageList.innerHTML = '<div class="loading">📊 暂无数据</div>';
            return;
        }
        
        // 转换为数组并排序
        const players = Object.keys(userData).map(uid => ({
            uid: uid,
            nickname: `玩家_${uid}`,
            ...userData[uid]
        }));
        
        // 按总伤害排序（从高到低）
        players.sort((a, b) => b.total_damage.total - a.total_damage.total);
        
        // 计算百分比（第一名为100%）
        const maxDamage = players.length > 0 ? players[0].total_damage.total : 1;
        
        // 生成HTML
        let html = '';
        players.forEach((player, index) => {
            const rank = index + 1;
            const percentage = Math.round((player.total_damage.total / maxDamage) * 100);
            const critRate = ((player.total_count.critical / player.total_count.total) * 100).toFixed(1);
            const luckyRate = ((player.total_count.lucky / player.total_count.total) * 100).toFixed(1);
            
            const rankClass = rank <= 3 ? `rank-${rank}` : '';
            
            html += `
                <div class="damage-item ${rankClass}">
                    <div class="player-info">
                        <div class="player-name">${player.nickname}</div>
                        <div class="rank-badge">#${rank}</div>
                    </div>
                    <div class="damage-stats">
                        <div class="stat-row">
                            <span class="stat-label">总伤害:</span>
                            <span class="stat-value">${formatNumber(player.total_damage.total)}</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">DPS:</span>
                            <span class="stat-value">${player.total_dps.toFixed(0)}</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">暴击率:</span>
                            <span class="stat-value">${critRate}%</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">幸运率:</span>
                            <span class="stat-value">${luckyRate}%</span>
                        </div>
                    </div>
                    <div class="percentage-bar">
                        <div class="percentage-fill" style="width: ${percentage}%"></div>
                    </div>
                </div>
            `;
        });
        
        damageList.innerHTML = html;
        
    } catch (error) {
        console.error('更新显示失败:', error);
        damageList.innerHTML = `<div class="loading">❌ 连接失败: ${error.message}</div>`;
    }
}

// 格式化数字
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

// 显示错误
function showError(message) {
    const damageList = document.getElementById('damageList');
    damageList.innerHTML = `<div class="loading">❌ ${message}</div>`;
}

// 开始数据刷新
function startDataRefresh() {
    // 立即更新一次
    updateDisplay();
    
    // 清除现有定时器
    if (refreshTimer) {
        clearInterval(refreshTimer);
    }
    
    // 设置新的定时器
    refreshTimer = setInterval(updateDisplay, settings.refreshInterval);
}

// 停止数据刷新
function stopDataRefresh() {
    if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
    }
}

// 设置面板相关函数
function toggleSettings() {
    const panel = document.getElementById('settingsPanel');
    panel.classList.toggle('hidden');
}

function hideSettings() {
    const panel = document.getElementById('settingsPanel');
    panel.classList.add('hidden');
}

function updateSettingsUI() {
    document.getElementById('opacitySlider').value = settings.opacity;
    document.getElementById('opacityValue').textContent = Math.round(settings.opacity * 100) + '%';
    document.getElementById('widthInput').value = settings.width;
    document.getElementById('heightInput').value = settings.height;
    document.getElementById('alwaysOnTopCheck').checked = settings.alwaysOnTop;
    document.getElementById('refreshInterval').value = settings.refreshInterval;
}

// 设置更新函数
async function updateOpacity() {
    const opacity = parseFloat(document.getElementById('opacitySlider').value);
    document.getElementById('opacityValue').textContent = Math.round(opacity * 100) + '%';
    
    settings.opacity = opacity;
    await ipcRenderer.invoke('update-settings', { opacity });
}

async function updateSize() {
    const width = parseInt(document.getElementById('widthInput').value);
    const height = parseInt(document.getElementById('heightInput').value);
    
    settings.width = width;
    settings.height = height;
    await ipcRenderer.invoke('update-settings', { width, height });
}

async function updateAlwaysOnTop() {
    const alwaysOnTop = document.getElementById('alwaysOnTopCheck').checked;
    
    settings.alwaysOnTop = alwaysOnTop;
    await ipcRenderer.invoke('update-settings', { alwaysOnTop });
}

function updateRefreshInterval() {
    const interval = parseInt(document.getElementById('refreshInterval').value);
    settings.refreshInterval = interval;
    
    // 重新启动数据刷新
    startDataRefresh();
}

async function resetPosition() {
    const newSettings = { x: 100, y: 100 };
    settings = { ...settings, ...newSettings };
    await ipcRenderer.invoke('update-settings', newSettings);
}

// 窗口控制函数
async function minimizeWindow() {
    await ipcRenderer.invoke('minimize-app');
}

async function closeWindow() {
    stopDataRefresh();
    await ipcRenderer.invoke('close-app');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    stopDataRefresh();
});
